package com.yc.study.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.study.entity.UserRole;
import com.yc.study.mapper.UserRoleMapper;
import com.yc.study.service.IUserRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 服务实现类
 *
 * @author 王妍
 * @since 2022-02-20
 */
@Service
@AllArgsConstructor
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements IUserRoleService {

  private final UserRoleMapper userRoleMapper;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void configureRoleForUser(Long userId, List<Long> roleIds) {
    userRoleMapper.delete(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
    roleIds.stream()
        .map(
            roleId -> {
              final UserRole userRole = new UserRole();
              userRole.setRoleId(roleId);
              userRole.setUserId(userId);
              return userRole;
            })
        .forEach(userRoleMapper::insert);
  }
}
